#!/usr/bin/Rscript
##########################################################################################
# Issue Ownership and Agenda Setting in the 2019 Swiss National Elections
##########################################################################################
# Description:
# Script for Figure 1
##########################################################################################
# Content
##########################################################################################
# 1) Dependencies
# 2) Startup
# 3) Load Data
# 4) Transform Data
# 5) Figure 1
##########################################################################################
# 1) Dependencies
##########################################################################################
library(dplyr)
library(tidyverse)
library(data.table)
library(readr)
library(lubridate)
library(ggplot2)
library(ggExtra)
library(ggeffects)
library(ggrepel)
library(ggforce)
library(igraph)
library(graphlayouts)
library(ggraph)
library(scales)
library(purrr)
library(magrittr)
library(cowplot)
library(sysfonts)
##########################################################################################
# 2) Startup
##########################################################################################
rm(list=ls())
# - set dir
args = commandArgs()

scriptName = args[substr(args,1,7) == '--file=']

if (length(scriptName) == 0) {
  scriptName <- rstudioapi::getSourceEditorContext()$path
} else {
  scriptName <- substr(scriptName, 8, nchar(scriptName))
}

pathName = substr(
  scriptName, 
  1, 
  nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2])
)


# - load fonts used in plots
sysfonts::font_add_google("Montserrat", "Montserrat")
sysfonts::font_add_google("Roboto", "Roboto")

# - load ddl theme
suppressMessages(suppressWarnings(source('../ggplot_theme_ddl.R')))
# - pre-setup for figure 1
ddl_theme_2 <- theme(legend.position = "bottom", legend.title = element_blank(), 
                     strip.background = element_blank(), strip.text = element_text(color = "black"),
                     axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.0, size = 16, color = "black"),  
                     axis.text.y = element_text(hjust=0, size = 16, color = "black"),
                     axis.ticks.y = element_blank(),
                     strip.text.x = element_text(size = 16, color = "black"),
                     axis.title = element_text(size = 16, color = "black"),
                     legend.text = element_text(size = 16, color = "black"),
                     plot.title = element_blank(),
                     plot.margin = unit(c(.5,.5,.5,.5), "cm"),
                     legend.key.size = unit(1.5,"line"),
                     legend.key = element_blank(),
                     axis.line.x = element_line(color="black", size = .5),
                     axis.line.y = element_line(color="black", size = .5),
                     panel.spacing.y = unit(2, "lines"),
                     panel.spacing.x = unit(.8, "lines")) 

# - set directory
setwd(pathName)
parent_path <- getwd()
##########################################################################################
# 3) Load Data
##########################################################################################
panel <- read_csv("../Data/1184_Selects2019_Panel_Data_v1.0.0.csv", col_types = cols(W1_f20210rec3 = col_double()))
##########################################################################################
# 4) Transform Data
##########################################################################################
ownership <- colnames(panel)[str_detect(colnames(panel),"f15330")]
issues <- unique(str_replace(ownership,"W[1-3]_",""))
names(issues) <- c("Europe","Immigation","Social Policy","Environment","Economic Policy")

df <- panel %>% 
  mutate_at(vars(contains("f15330")),
            funs(case_when(.==1~"FDP",
                           .==2~"CVP",
                           .==3~"SP",
                           .==4~"SVP",
                           .==5~"Greens",
                           .==6~"GLP",
                           .==7~"BDP",
                           .==8~"Lega",
                           .==9~"MCG",
                           .==20~"Others",
                           TRUE~NA_character_))) 
##########################################################################################
# 5) Figure 1
##########################################################################################
variables_panel <- c("W1_f15330a", "W1_f15330d", "W1_f15330b")
topics_panel <- c("Europe", "Environment", "Immigration")

for(i in 1:length(variables_panel)) {
  tmp <- df %>% dplyr::select(c("id", variables_panel[i])) %>% 
    pivot_longer(-id,names_to="vars",values_to="vals") %>% 
    dplyr::filter(!is.na(vals) == T) %>% 
    dplyr::filter(is.na(variables_panel[i]) == F) %>%
    dplyr::group_by(vals) %>%
    summarise(n = n()) %>% mutate(topic = topics_panel[i])
  if(i == 1){
    pl <- tmp
  } else {
    pl <- dplyr::bind_rows(pl,tmp)
  }
  rm(tmp)
}

pl <- pl %>%  dplyr::group_by(topic) %>% 
  dplyr::mutate(n.cand = sum(n)) %>%
  dplyr::group_by(vals,n.cand,topic) %>% 
  dplyr::mutate(frac = n / sum(n.cand)) %>% 
  dplyr::filter(vals %in% c("FDP", "CVP", "SP", "SVP", "Greens", "GLP")) %>% 
  dplyr::ungroup() %>% 
  dplyr::arrange(topic, frac) %>% 
  dplyr::mutate(order = row_number()) %>% 
  dplyr::mutate(topic = fct_relevel(topic, "Environment", "Europe", "Immigration")) 

ggplot(data = pl, aes(y = frac, x = order, fill = topic)) +
  geom_col(position = position_dodge(width = 0.8), width=0.75, alpha = 0.75) +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  scale_x_continuous(breaks = pl$order,
                     labels = pl$vals,
                     expand = c(0,0)) +
  scale_y_continuous(labels = scales::percent) +
  scale_color_manual(labels = c("Environment","Europe","Immigration"), values = c("#009E73","#0072B2","#999999")) +
  scale_fill_manual(labels = c("Environment","Europe","Immigration"), values = c("#009E73","#0072B2","#999999")) +
  labs(x = "Party", y = "Share of respondents", title = "Which is the most competent Party in the folowing Topics:") +
  coord_flip() +
  ddl_theme_2 +
  theme(legend.position = "none", legend.title = element_text(size = 16, color = "black"), 
        strip.background = element_blank(), strip.text = element_text(color = "black"),
        axis.text.x = element_text(angle = 0, hjust = .5, vjust = 0, size = 16, color = "black"),  
        axis.text.y = element_text(hjust=.5, size = 16, color = "black"),
        strip.text.x = element_text(size = 19, color = "black"),
        axis.title = element_text(size = 19, color = "black"),
        plot.title = element_blank(),
        legend.text = element_text(size = 16, color = "black"),
        legend.key = element_blank(),
        plot.margin = unit(c(.5,1.3,.5,.5), "cm"),
        legend.key.size = unit(1.5,"line"),
        axis.line.x = element_line(color="black", size = .5),
        axis.line.y = element_line(color="black", size = .5),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

ggsave(filename = paste0("../images/figure_1.pdf"),  width = 24, height = 12, device = cairo_pdf, units = "cm")
